package com.chebaohui.iqs.sdk.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;

public class RsaFuc {

	public static String getDecryption(String value) throws Exception {
		byte[] by = getOuString(value);
		return getPrivate(by, SKEY);
	}

	private static String getPrivate(byte[] b, String key) throws Exception {
		byte[] bc = decryptByPrivateKey(b, key);
		return new String(bc);
	}

	private static final String SKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIctIu23JE1S86qjR8beLS0YHL8D6c870nYDUOy1o3IY9+0N5pULGtsRlUf05SZGAuwVhGtSlFh9XPNfRkm0E3JIucPBqMb2toOZQH9X6orOu5kgCnr9YjneH4Vv4uscAB/UDCa3iuboy7BQujMLKr2C+51Nah+dJgz+QfAPM/wbAgMBAAECgYBeGx068woRztMWE3Av0ZMP1r6EeLv4asQ9JlfbQyTTlPBdFxVU45NBub78hlBVUd5M7znt4WKnLDdesxBi1TvHiteNQMuewzVTLqdcgKCd0bFiGInqTVFWN9/+l9w+TMKf1ROcm/s5mZexutySUd1f2Q+evijv+uK8svLkG9f3WQJBAM452CxjgXZx6VhX4uEzgXeiChx78yr9DKzs7zxsaUpSv4h+9IVFtZnXUx42ozccJlXJuaUR2sBaTdrcsy8KnS8CQQCnzVKo+hwMWcav1ZEUQ7Hyo91Gpw0kfb5xHz+s3M+R8VruxwetxibRI2vd6nF/qJ5bKx+iZiN0sRXvml4dzwzVAkBElSIaKQFuBZYHpjqykDF3OrFIJcSJwFwNykIJgzhE2l4OI8Jn6/Xn8p8Wxi7jbf4lu498oQJxw9ZuecUxWMNLAkEApsu5dq3mY4B5tx6a74G6yG2J7kjvD27OdrORH8r9qRw4P1EnmNx2iTykZBo+Z568ifL7pvnQFJZSL7FKDGdbYQJAdyWKvNMijWuI8I2oZ+qLSzZ2dYiuw6ND6RZnSTGktWt0rJfrq/FxWZEFkPRB3bK8MAWk2zmSTQxncRhjveBDSw==";
	private static final String KEY_ALGORTHM = "RSA";

	private static byte[] getOuString(String sendString) throws Exception {
		String[] list = sendString.split("#");
		byte[] b = new byte[list.length];
		for (int i = 0; i < list.length; i++)
			b[i] = Byte.valueOf(list[i]);
		return b;
	}

	private static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
		// 对私钥解密
		byte[] keyBytes = decryptBASE64(key);

		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		return cipher.doFinal(data);
	}

	private static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}
}
